<template>
  <div class="app-container">
    <el-form
      ref="listFilterRef"
      :model="list.filter"
      inline
      class="list-filter"
    >
      <el-form-item prop="identityCard">
        <el-input v-model="list.filter.identityCard" placeholder="身份证" clearable>
          <i slot="prefix" class="el-input__icon el-icon-search" />
        </el-input>
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="list.filter.name" placeholder="会员姓名" clearable>
          <i slot="prefix" class="el-input__icon el-icon-search" />
        </el-input>
      </el-form-item>
      <el-form-item prop="cardNum">
        <el-input v-model="list.filter.cardNum" placeholder="卡号" clearable>
          <i slot="prefix" class="el-input__icon el-icon-search" />
        </el-input>
      </el-form-item>
      <el-form-item prop="regEndTime">
        <TimeRangePicker :start.sync="list.filter.regBeginTime" :end.sync="list.filter.regEndTime" placeholder="开始注册时间/结束注册时间" />
      </el-form-item>
      <el-form-item prop="levelId">
        <!-- <Selector v-model="list.filter.levelId" placeholder="会员等级" :options="options.level" optionKey="id/levelName" /> -->
        <KiSelect 
          v-model="list.filter.levelId" 
          :props="{ label: 'levelName', value: 'id'}"
          :options="options.level" placeholder="会员等级" 
        />
      </el-form-item>
      <el-form-item prop="regSource">
        <KiSelect v-model="list.filter.regSource" placeholder="注册来源" :options="dict.reg_source" />
      </el-form-item>
      <el-form-item prop="tagId">
        <KiSelect 
          v-model="list.filter.tagId" 
          :props="{ label: 'name', value: 'id'}" 
          :options="options.tag" 
          placeholder="会员标签" 
        />
      </el-form-item>
      <el-form-item prop="memberType">
        <KiSelect
          v-model="list.filter.memberType"
          placeholder="会员类别"
          :options="options.memberType"
          :props="{ value: 'id',label: 'name'}"
        />
      </el-form-item>
      <el-button @click="reset">重置</el-button>
    </el-form>

    <div class="table-operation">
      <span>
        <AuthButton @click="c" name="注册" />
        <ExportExcel
          url="sot-admin-api/vip/vip-member-info/exportData"
          :param="list.filter"
        />
        <AuthButton
          @click="
            () => {
              memberType.show = true
            }
          "
          name="类别管理"
        />
      </span>
      <el-pagination
        v-bind="elPaginationProps"
        :total="list.total"
        :currentPage.sync="list.filter.pageNo"
        :pageSize.sync="list.filter.pageSize"
      />
    </div>

    <el-table v-loading="list.loading" :data="list.data" v-bind="tableProp">
      <el-table-column align="center" type="index" />
      <el-table-column label="身份证" prop="identityCard" />
      <el-table-column label="卡号" prop="cardNum" />
      <el-table-column label="会员来源" prop="dataSource" />
      <el-table-column label="会员姓名" prop="name" />
      <el-table-column label="性别" prop="sex">
        <template slot-scope="{ row }">
          <el-tag :type="formatValue(row.sex,options.sex,'value').type">{{formatValue(row.sex,options.sex,'value').text}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="age" />
      <el-table-column label="注册来源" prop="regSource">
        <template slot-scope="{ row }">
          {{ row.regSource | $value2label(dict.reg_source) }}
        </template>
      </el-table-column>
      <el-table-column label="等级名称" prop="levelName" />
      <el-table-column label="消费总额" prop="totalConsumption">
        <template slot-scope="{ row }">
          {{ row.totalConsumption | $cent2yuan }}
        </template>
      </el-table-column>
      <el-table-column label="注册时间" prop="regTime" />
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row: { id, status } }">
          <KiPopSwitch
            v-bind="popSwitchProps(status)"
            @change="updateStatus({ id, status: status ^ 1 })"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <AuthButton @click="r({id : row.id })" name="查看" />
          <AuthButton @click="u(row)" name="编辑" />
          <AuthButton @click="editTag(row)" name="编辑标签" circle>
            <i class="el-icon-price-tag" />
          </AuthButton>
          <AuthButton @click="d(row)" name="删除" />
        </template>
      </el-table-column>
    </el-table>

    <KiFormDialog
      :show.sync="form.show"
      :title="form.status === 'c' ? '会员注册' : formTitle"
      v-model="form.data.memberInfo"
      :submit="submit"
      :readonly="form.status === 'r'"
      ref="formRef"
    >
      <template #el-form>
        <template v-if="form.status !== 'r'">
          <el-form-item label="会员姓名" prop="name" :verify="nameRules">
            <el-input v-model="form.data.memberInfo.name" clearable maxlength="4" show-word-limit />
          </el-form-item>
          <el-form-item label="身份证" prop="identityCard" :verify="{ type: 'idCard' }">
            <el-input v-model="form.data.memberInfo.identityCard" clearable />
          </el-form-item>
          <el-form-item label="性别" prop="sex" verify>
            <el-radio v-model="form.data.memberInfo.sex" :label="v.value" v-for="(v, i) of options.sex.filter(v => v.value !== 0)" :key="i">
              {{ v.text }}
            </el-radio>
          </el-form-item>
          <el-form-item label="手机号" prop="phone" :verify="{ type: 'phone' }">
            <el-input v-model="form.data.memberInfo.phone" clearable>
              <SmsButton slot="append" @click="sendPhoneCode" ref="smsBtnRef" />
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="smsCode" :verify="{ type: 'verifyCode' }">
            <el-input v-model="form.data.memberInfo.smsCode" clearable />
          </el-form-item>
          <!-- <el-form-item label="人脸认证" prop="__avatar" verify v-if="form.status === 'c'">
            <el-radio-group
              v-model="form.data.memberInfo.__avatarType"
              @change="
                () => {
                  $set(form.data.memberInfo, '__avatar', null)
                  $set(form.data.memberInfo, '__avatarBase64', null)
                }
              "
            >
              <el-radio label="camera">
                摄像头拍照
              </el-radio>
              <el-radio label="photo">
                上传照片
              </el-radio>
            </el-radio-group>

            <div v-show="form.data.memberInfo.__avatarType === 'camera'">
              <el-button
                @click="
                  () => {
                    showCamera = true
                  }
                "
                type="primary"
                plain
                class="block"
              >
                打开摄像头
              </el-button>
              <PicViewer class="mt-2.5" :value="form.data.memberInfo.__avatarBase64" />
              <Camera
                ref="camera"
                :show.sync="showCamera"
                @confirm="
                  ({ file, base64 }) => {
                    $set(form.data.memberInfo, '__avatar', file)
                    $set(form.data.memberInfo, '__avatarBase64', base64)
                  }
                "
              />
            </div>
            <Filepool v-show="form.data.memberInfo.__avatarType === 'photo'" v-model="form.data.memberInfo.__avatar" :count="1" fileType="image" :upload="false" />
          </el-form-item> -->
          <el-form-item label="会员类别" prop="memberType">
            <KiSelect
              v-model="form.data.memberInfo.memberType"
              :options="options.memberType"
              :props="{
                value: 'id',
                label: 'name'
              }"
            />
          </el-form-item>
          <!-- <el-form-item label="办理人员" prop="processor" :verify="nameRules">
            <el-input v-model="form.data.memberInfo.processor" clearable maxlength="4" show-word-limit />
          </el-form-item> -->
        </template>
        <template v-else>
          <template v-if="form.data.memberInfo">
            <h3 class="subtitle"><span>基本信息</span></h3>
            <div class="flex justify-between">
              <preview-table class="flex-1">
                <tr>
                  <td>用户ID</td>
                  <td>{{ form.data.memberInfo.id }}</td>
                </tr>
                <tr>
                  <td>卡号</td>
                  <td>{{ form.data.memberInfo.cardNum }}</td>
                </tr>
                <tr>
                  <td>手机号</td>
                  <td>{{ form.data.memberInfo.phone }}</td>
                </tr>
                <tr>
                  <td>会员级别</td>
                  <td>{{ form.data.memberInfo.levelName }}</td>
                </tr>
                <tr>
                  <td>会员类别</td>
                  <td>{{ form.data.memberInfo.memberTypeName }}</td>
                </tr>
                <tr v-if="form.data.memberInfo.regSource === '2'">
                  <td>办理人员</td>
                  <td>{{ form.data.memberInfo.processor }}</td>
                </tr>
              </preview-table>

              <PicViewer class="flex-1 ml-4" :value="form.data.memberInfo.avatar" />
            </div>
          </template>

          <template v-if="form.data.memberInfo">
            <el-divider />
            <h3 class="subtitle"><span>会员资料</span></h3>
            <preview-table>
              <tr>
                <td>姓名</td>
                <td>{{ form.data.memberInfo.name }}</td>
                <td>性别</td>
                <td>{{ form.data.memberInfo.sex | $value2label(options.sex, 'value/text') }}</td>
              </tr>
              <tr>
                <td>生日</td>
                <td>{{ form.data.memberInfo.birthDate }}</td>
                <td>身份证号</td>
                <td>{{ form.data.memberInfo.identityCard }}</td>
              </tr>
              <tr>
                <td>注册来源</td>
                <td>{{ form.data.memberInfo.regSource | $value2label(dict.reg_source) }}</td>
                <td>注册时间</td>
                <td>{{ form.data.memberInfo.regTime }}</td>
              </tr>
              <!--<tr>
                <td>收货地址</td>
                <td>{{ form.data.addressInfo && form.data.addressInfo.address }}</td>
              </tr>-->
            </preview-table>
          </template>

          <template v-if="form.data.memberTags && form.data.memberTags.length">
            <el-divider />
            <h3 class="subtitle"><span>会员标签</span></h3>
            <el-tag v-for="(v, i) of form.data.memberTags" :key="i">{{ v.tagName }}</el-tag>
          </template>

          <template v-if="form.data.memberAssetInfo">
            <el-divider />
            <h3 class="subtitle"><span>会员资产</span></h3>
            <preview-table>
              <tr>
                <td>当前余额</td>
                <td>{{ form.data.memberAssetInfo.balance | $cent2yuan }}</td>
                <td>当前积分</td>
                <td>{{ form.data.memberAssetInfo.integral }}</td>
              </tr>
              <tr>
                <td>累计充值金额</td>
                <td>{{ form.data.memberAssetInfo.totalRecharge | $cent2yuan }}</td>
                <td>累计积分</td>
                <td>{{ form.data.memberAssetInfo.totalIntegral }}</td>
              </tr>
            </preview-table>
          </template>

          <template v-if="form.data.consumerBehaviorInfo">
            <el-divider />
            <h3 class="subtitle"><span>消费行为</span></h3>
            <preview-table>
              <tr>
                <td>累计消费金额</td>
                <td>{{ form.data.consumerBehaviorInfo.sumPrice | $cent2yuan }}</td>
                <td>累计消费次数</td>
                <td>{{ form.data.consumerBehaviorInfo.sumCount }}</td>
              </tr>
              <tr>
                <td>订单平均消费额</td>
                <td>{{ form.data.consumerBehaviorInfo.avgPrice | $cent2yuan }}</td>
                <td>订单平均商品数</td>
                <td>{{ form.data.consumerBehaviorInfo.avgQuantity }}</td>
              </tr>
              <tr>
                <td>消费频次</td>
                <td>
                  {{ $isEmpty(form.data.consumerBehaviorInfo.frequency) ? '' : form.data.consumerBehaviorInfo.frequency + ' 次/月' }}
                </td>
                <td>首次消费时间</td>
                <td>{{ form.data.consumerBehaviorInfo.minOrderTime }}</td>
              </tr>
              <tr>
                <td>最近一次消费时间</td>
                <td>{{ form.data.consumerBehaviorInfo.maxOrderTime }}</td>
              </tr>
            </preview-table>
          </template>

          <template v-if="form.data.consumerPreferences && form.data.consumerPreferences.length">
            <el-divider />
            <h3 class="subtitle"><span>购物偏好</span></h3>
            <el-table stripe v-loading="form.loading" :data="form.data.consumerPreferences" border fit highlight-current-row>
              <el-table-column align="center" type="index" />
              <!--<el-table-column label="排名" prop=""/>-->
              <el-table-column label="分类名称" prop="businessTypeName" />
              <el-table-column label="消费数量" prop="quantity" />
              <el-table-column label="消费金额">
                <template slot-scope="{ row }">
                  {{ row.price | $cent2yuan }}
                </template>
              </el-table-column>
            </el-table>
          </template>
        </template>
      </template>
    </KiFormDialog>

    <KiFormDialog :show.sync="importList.show" title="导入" v-model="importList.data" :submit="importListSubmit">
      <template #el-form>
        <div class="mb20">
          <ExportExcel
            url="sot-admin-api/vip/vip-member-info/downloadImportTpl"
            :param="{}"
            name="模板下载"
          />
        </div>
        <el-form-item prop="file" verify>
          <Filepool v-model="importList.data.file" :count="1" fileType="excel" :upload="false" />
        </el-form-item>
      </template>
    </KiFormDialog>

    <KiFormDialog :show.sync="tag.show" title="编辑标签" v-model="tag.data" :submit="tagSubmit">
      <template #el-form>
        <el-form-item prop="tagIdList">
          <el-transfer
            filterable
            :filter-method="filterMethod"
            :titles="['待选', '已选']"
            v-model="tag.data.memberTags"
            :data="tag.data.manualTags"
            :props="{
              key: 'tagId',
              label: 'tagName'
            }"
          />
        </el-form-item>
      </template>
    </KiFormDialog>

    <KiFormDialog :show.sync="memberType.show" title="类别管理" v-model="memberType.data" :submit="memberTypeSubmit">
      <DynamicTag v-model="memberType.data" addName="新增类别" objectKey="name" />
    </KiFormDialog>
  </div>
</template>

<script>
import { DynamicTag } from 'dynamic-tag'
import pageMixin from '@/utils/pageMixin'
import useAdmateAdapter from '@/utils/useAdmateAdapter'
import previewTable from "@/components/preview-table";
import SmsButton from "@/components/SmsButton";
export default {
  mixins: [pageMixin],
  components: {  
    SmsButton, 
    previewTable,
    DynamicTag 
  },
  setup: () => useAdmateAdapter({
    urlPrefix: 'sot-admin-api/vip/vip-member-info',
    form: {
      data: {
        memberInfo: {
          // __avatarType: 'camera'
        }
      }
    }
  }),
  data() {
    return {
      loading: false,
      options: {
        sex: [
          { value: 0, text: '未知', type: 'info' },
          { value: 1, text: '男' },
          { value: 2, text: '女', type: 'danger' }
        ],
        tag: [],
        level: [],
        memberType: []
      },
      tag: {
        show: false,
        data: {
          tagIdList__: [],
          tagIdList: [],
          memberId: null
        }
      },
      memberType: {
        show: false,
        data: []
      },
      filterMethod(query, item) {
        return item.tagName.indexOf(query) > -1
      },
      importList: {
        show: false,
        data: {}
      },
      // showCamera: false,
    }
  },
  watch: {
    'memberType.show': {
      handler(v) {
        if (v) this.memberTypeDataGetter();
      },
      deep: true,
    },
    'tag.show': {
      handler(v) {
        if (v) this.tagDataGetter();
      },
      deep: true,
    },
  },
  created() {
    this.$POST('sot-admin-api/vip/vip-tag/queryForList').then(({ data }) => {
      this.options.tag = data || []
    })
    this.$POST('sot-admin-api/vip/vip-level/queryForList').then(({ data }) => {
      this.options.level = data || []
    })
    this.$POST('sot-admin-api/vip/vip-member-type/listForSelect').then(({ data }) => {
      this.options.memberType = data || []
    })
  },
  methods: {
    // 转换sex数据
    formatValue(value,list,keyVal="value"){
      value = value==null ? 0 : value // 对null数据特殊处理
      return list.filter(item=>{
        return item[keyVal] == value
      })[0]
    },
    nameRules(rule, value, callback){
      if(!this.$notEmpty(value)){
        callback(new Error('必填项'))
      }
      let errInfo = ''
      if (this.$notEmpty(value) && !/[\u4e00-\u9fa5]{2,4}/.test(value)) {
        errInfo = '请输入2~4位汉字'
      }
      callback(errInfo ? new Error(errInfo) : undefined)
    },
    async submit() {
      return this.submitForm(this.form.data.memberInfo)
    },
    sendPhoneCode(e) {
      this.$refs.formRef.$refs.elForm.validateField('phone', err => {
        if (err) {
          this.$swal.error('请输入正确的手机号')
        } else {
          // 调用短信接口
          this.$POST('sot-admin-api/vip/vip-sms/sendPhoneCode', { 
            phone: this.form.data.memberInfo.phone 
          }).then(res => {
            this.$refs.smsBtnRef.loading = false
            if (res.errorCode == '00000') {
              this.$refs.smsBtnRef.send() // 已发送
            } else {
              this.$swal.error(res.message)
            }
          })
          .finally(_ => {
            this.$refs.smsBtnRef.loading = false
          })
        }
      })
    },
    editTag(row) {
      this.tag.data.memberId = row.id
      this.tag.show = true
    },
    tagDataGetter() {
      return this.$POST('sot-admin-api/vip/vip-member-info/queryMemberTagForUpdate', {
        id: this.tag.data.memberId
      }).then(({ data }) => {
        if (data) {
          data.manualTags = [...(data.manualTags || []), ...(data.memberTags || [])]
          this.tag.data = {
            ...data,
            manualTags: data.manualTags.map(v => ({
              ...v,
              disabled: v.tagType === 1
            })),
            memberTags: data.memberTags.map(v => v.tagId)
          }
        }
      })
    },
    tagSubmit() {
      return this.$POST('sot-admin-api/vip/vip-member-info/updateMemberTag', {
        memberId: this.tag.data.memberId,
        tagIdList: this.tag.data.memberTags
      })
    },
    importListSubmit() {
      return this.$upload('sot-admin-api/vip/vip-member-info/importData', this.importList.data)
    },
    memberTypeDataGetter() {
      return this.$POST('sot-admin-api/vip/vip-member-type/queryForList').then(({ data }) => {
        this.memberType.data = data || []
      })
    },
    memberTypeSubmit() {
      return this.$POST('sot-admin-api/vip/vip-member-type/batchSave', this.memberType.data)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-transfer {
  text-align: center;

  .el-transfer-panel {
    width: 31%;
    text-align: left;

    .el-input {
      width: auto !important;
    }
  }
}
</style>
